package cache

import (
	"fmt"
	"time"
)

// ----------------------------------------
//  Redis 计数器
// ----------------------------------------
type RedisCounter struct {
	client *RedisClient
	key    string
}

func CreateRedisCounter(client *RedisClient, key string, args ...interface{}) *RedisCounter {
	if len(args) > 0 {
		key = fmt.Sprintf(key, args...)
	}

	return &RedisCounter{client: client, key: key}
}

func (c *RedisCounter) Key() string {
	return c.key
}

func (c *RedisCounter) Set(count int64, expiration time.Duration) error {
	return c.client.Client.Set(c.key, count, expiration).Err()
}

func (c *RedisCounter) Zero(expiration time.Duration) error {
	return c.Set(0, expiration)
}

func (c *RedisCounter) Incr() error {
	return c.client.Client.Incr(c.key).Err()
}

func (c *RedisCounter) IncrOfMarker(marker *RedisMarker) error {
	if ok, err := marker.Mark(); err != nil {
		return err
	} else {
		if ok {
			return c.client.Client.Incr(c.key).Err()
		} else {
			return nil
		}
	}
}

func (c *RedisCounter) Decr() error {
	return c.client.Client.Decr(c.key).Err()
}

func (c *RedisCounter) DecrOfMarker(marker *RedisMarker) error {
	if ok, err := marker.Unmark(); err != nil {
		return err
	} else {
		if ok {
			return c.client.Client.Incr(c.key).Err()
		} else {
			return nil
		}
	}
}

func (c *RedisCounter) Count() (int64, error) {
	return c.client.Client.Get(c.key).Int64()
}

func (c *RedisCounter) Destroy() error {
	return c.client.Client.Del(c.key).Err()
}
